package com.ruoyi.manage.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.manage.domain.CrMatchingRecord;
import com.ruoyi.manage.service.ICrMatchingRecordService;

/**
 * 智能匹配记录Controller
 * 
 * @author ruoyi
 * @date 2024-09-24
 */
@RestController
@RequestMapping("/campus/matchingRecord")
public class CrMatchingRecordController extends BaseController
{
    @Autowired
    private ICrMatchingRecordService crMatchingRecordService;

    /**
     * 查询智能匹配记录列表
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:list')")
    @GetMapping("/list")
    public TableDataInfo list(CrMatchingRecord crMatchingRecord)
    {
        startPage();
        List<CrMatchingRecord> list = crMatchingRecordService.selectCrMatchingRecordList(crMatchingRecord);
        return getDataTable(list);
    }

    /**
     * 导出智能匹配记录列表
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:export')")
    @Log(title = "智能匹配记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CrMatchingRecord crMatchingRecord)
    {
        List<CrMatchingRecord> list = crMatchingRecordService.exportMatchingRecords(crMatchingRecord);
        ExcelUtil<CrMatchingRecord> util = new ExcelUtil<CrMatchingRecord>(CrMatchingRecord.class);
        util.exportExcel(response, list, "智能匹配记录数据");
    }

    /**
     * 获取智能匹配记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:query')")
    @GetMapping(value = "/{matchingId}")
    public AjaxResult getInfo(@PathVariable("matchingId") Long matchingId)
    {
        return success(crMatchingRecordService.selectCrMatchingRecordByMatchingId(matchingId));
    }

    /**
     * 新增智能匹配记录
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:add')")
    @Log(title = "智能匹配记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrMatchingRecord crMatchingRecord)
    {
        return toAjax(crMatchingRecordService.insertCrMatchingRecord(crMatchingRecord));
    }

    /**
     * 修改智能匹配记录
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:edit')")
    @Log(title = "智能匹配记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CrMatchingRecord crMatchingRecord)
    {
        return toAjax(crMatchingRecordService.updateCrMatchingRecord(crMatchingRecord));
    }

    /**
     * 删除智能匹配记录
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:remove')")
    @Log(title = "智能匹配记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{matchingIds}")
    public AjaxResult remove(@PathVariable Long[] matchingIds)
    {
        return toAjax(crMatchingRecordService.deleteCrMatchingRecordByMatchingIds(matchingIds));
    }

    // ========== 业务相关接口 ==========

    /**
     * 生成智能推荐（通用接口）
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:generate') or @ss.hasPermi('campus:student:recommendation:generate') or @ss.hasRole('student')")
    @Log(title = "生成智能推荐", businessType = BusinessType.INSERT)
    @PostMapping("/generateRecommendation")
    public AjaxResult generateRecommendation(@RequestBody Map<String, Object> requestData)
    {
        try {
            // 从请求数据中获取studentId
            Long studentId;
            if (requestData.containsKey("studentId")) {
                Object studentIdObj = requestData.get("studentId");
                if (studentIdObj instanceof Number) {
                    studentId = ((Number) studentIdObj).longValue();
                } else if (studentIdObj instanceof String) {
                    studentId = Long.parseLong((String) studentIdObj);
                } else {
                    return error("无效的studentId格式");
                }
            } else {
                return error("缺少studentId参数");
            }
            
            List<CrMatchingRecord> recommendations = crMatchingRecordService.generateMatchingRecommendations(studentId, 10);
            return success(recommendations);
        } catch (Exception e) {
            return error("生成推荐失败: " + e.getMessage());
        }
    }

    /**
     * 为学生生成匹配推荐
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:generate') or @ss.hasRole('student')")
    @Log(title = "生成学生匹配推荐", businessType = BusinessType.INSERT)
    @PostMapping("/generate/student/{studentId}")
    public AjaxResult generateMatchingRecommendations(@PathVariable Long studentId, 
                                                     @RequestParam(defaultValue = "5") int limit)
    {
        List<CrMatchingRecord> recommendations = crMatchingRecordService.generateMatchingRecommendations(studentId, limit);
        return success(recommendations);
    }

    /**
     * 为招聘生成匹配推荐
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:generate')")
    @PostMapping("/generate/recruitment/{recruitmentId}")
    public AjaxResult generateRecruitmentRecommendations(@PathVariable Long recruitmentId, 
                                                        @RequestParam(defaultValue = "10") int limit)
    {
        List<CrMatchingRecord> recommendations = crMatchingRecordService.generateRecruitmentRecommendations(recruitmentId, limit);
        return success(recommendations);
    }

    /**
     * 计算学生与招聘的匹配度
     */
    @PreAuthorize("@ss.hasRole('student')")
    @GetMapping("/calculate")
    public AjaxResult calculateMatchingScore(@RequestParam Long studentId, @RequestParam Long recruitmentId)
    {
        BigDecimal score = crMatchingRecordService.calculateMatchingScore(studentId, recruitmentId);
        return success(score);
    }

    /**
     * 计算技能匹配度
     */
    @PreAuthorize("@ss.hasRole('student')")
    @GetMapping("/calculate/skill")
    public AjaxResult calculateSkillMatchingScore(@RequestParam Long studentId, @RequestParam Long recruitmentId)
    {
        BigDecimal score = crMatchingRecordService.calculateSkillMatchingScore(studentId, recruitmentId);
        return success(score);
    }

    /**
     * 计算兴趣匹配度
     */
    @PreAuthorize("@ss.hasRole('student')")
    @GetMapping("/calculate/interest")
    public AjaxResult calculateInterestMatchingScore(@RequestParam Long studentId, @RequestParam Long clubId)
    {
        BigDecimal score = crMatchingRecordService.calculateInterestMatchingScore(studentId, clubId);
        return success(score);
    }

    /**
     * 计算时间匹配度
     */
    @PreAuthorize("@ss.hasRole('student')")
    @GetMapping("/calculate/time")
    public AjaxResult calculateTimeMatchingScore(@RequestParam Long studentId, @RequestParam Long recruitmentId)
    {
        BigDecimal score = crMatchingRecordService.calculateTimeMatchingScore(studentId, recruitmentId);
        return success(score);
    }

    /**
     * 批量创建匹配记录
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:add')")
    @Log(title = "批量创建匹配记录", businessType = BusinessType.INSERT)
    @PostMapping("/batchCreate")
    public AjaxResult batchCreateMatchingRecords(@RequestBody List<CrMatchingRecord> matchingRecords)
    {
        int result = crMatchingRecordService.batchCreateMatchingRecords(matchingRecords);
        return success("成功创建 " + result + " 条匹配记录");
    }

    /**
     * 更新匹配记录状态
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:edit')")
    @PutMapping("/updateStatus/{matchingId}")
    public AjaxResult updateMatchingStatus(@PathVariable Long matchingId, @RequestParam String status)
    {
        return toAjax(crMatchingRecordService.updateMatchingStatus(matchingId, status));
    }

    /**
     * 根据学生ID查询匹配记录
     */
    @GetMapping("/student/{studentId}")
    public AjaxResult getMatchingsByStudent(@PathVariable Long studentId, 
                                          @RequestParam(required = false) String status)
    {
        List<CrMatchingRecord> matchings = crMatchingRecordService.selectMatchingsByStudentId(studentId, status);
        return success(matchings);
    }

    /**
     * 根据社团ID查询匹配记录
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:list')")
    @GetMapping("/club/{clubId}")
    public AjaxResult getMatchingsByClub(@PathVariable Long clubId, 
                                       @RequestParam(required = false) String status)
    {
        List<CrMatchingRecord> matchings = crMatchingRecordService.selectMatchingsByClubId(clubId, status);
        return success(matchings);
    }

    /**
     * 根据招聘ID查询匹配记录
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:list')")
    @GetMapping("/recruitment/{recruitmentId}")
    public AjaxResult getMatchingsByRecruitment(@PathVariable Long recruitmentId, 
                                              @RequestParam(required = false) String status)
    {
        List<CrMatchingRecord> matchings = crMatchingRecordService.selectMatchingsByRecruitmentId(recruitmentId, status);
        return success(matchings);
    }

    /**
     * 获取高匹配度的记录
     */
    @GetMapping("/highMatching")
    public AjaxResult getHighMatchingRecords(@RequestParam(defaultValue = "80") BigDecimal threshold,
                                           @RequestParam(defaultValue = "20") int limit)
    {
        List<CrMatchingRecord> records = crMatchingRecordService.getHighMatchingRecords(threshold, limit);
        return success(records);
    }

    /**
     * 获取学生的匹配统计
     */
    @GetMapping("/statistics/student/{studentId}")
    public AjaxResult getStudentMatchingStatistics(@PathVariable Long studentId)
    {
        Map<String, Object> statistics = crMatchingRecordService.getStudentMatchingStatistics(studentId);
        return success(statistics);
    }

    /**
     * 获取社团的匹配统计
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:list')")
    @GetMapping("/statistics/club/{clubId}")
    public AjaxResult getClubMatchingStatistics(@PathVariable Long clubId)
    {
        Map<String, Object> statistics = crMatchingRecordService.getClubMatchingStatistics(clubId);
        return success(statistics);
    }

    /**
     * 获取招聘的匹配统计
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:list')")
    @GetMapping("/statistics/recruitment/{recruitmentId}")
    public AjaxResult getRecruitmentMatchingStatistics(@PathVariable Long recruitmentId)
    {
        Map<String, Object> statistics = crMatchingRecordService.getRecruitmentMatchingStatistics(recruitmentId);
        return success(statistics);
    }

    /**
     * 获取匹配度分布统计
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:list')")
    @GetMapping("/statistics/distribution")
    public AjaxResult getMatchingScoreDistribution()
    {
        Map<String, Object> distribution = crMatchingRecordService.getMatchingScoreDistribution();
        return success(distribution);
    }

    /**
     * 重新计算匹配记录
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:edit')")
    @Log(title = "重新计算匹配记录", businessType = BusinessType.UPDATE)
    @PutMapping("/recalculate/{matchingId}")
    public AjaxResult recalculateMatching(@PathVariable Long matchingId)
    {
        return toAjax(crMatchingRecordService.recalculateMatching(matchingId));
    }

    /**
     * 批量重新计算匹配记录
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:edit')")
    @Log(title = "批量重新计算匹配记录", businessType = BusinessType.UPDATE)
    @PutMapping("/batchRecalculate")
    public AjaxResult batchRecalculateMatchings(@RequestParam(required = false) Long studentId,
                                               @RequestParam(required = false) Long recruitmentId)
    {
        int result = crMatchingRecordService.batchRecalculateMatchings(studentId, recruitmentId);
        return success("重新计算了 " + result + " 条匹配记录");
    }

    /**
     * 学生查看匹配推荐
     */
    @Log(title = "查看匹配推荐", businessType = BusinessType.OTHER)
    @PostMapping("/view/{matchingId}")
    public AjaxResult viewMatchingRecommendation(@PathVariable Long matchingId)
    {
        Long studentId = getUserId();
        return toAjax(crMatchingRecordService.viewMatchingRecommendation(matchingId, studentId));
    }

    /**
     * 学生对匹配结果进行反馈
     */
    @Log(title = "提交匹配反馈", businessType = BusinessType.UPDATE)
    @PutMapping("/feedback")
    public AjaxResult submitMatchingFeedback(@RequestBody Map<String, Object> params)
    {
        Long matchingId = Long.valueOf(params.get("matchingId").toString());
        Long studentId = getUserId();
        String feedback = (String) params.get("feedback");
        Boolean isAccurate = params.get("isAccurate") != null ? 
            Boolean.valueOf(params.get("isAccurate").toString()) : null;
        
        return toAjax(crMatchingRecordService.submitMatchingFeedback(matchingId, studentId, feedback, isAccurate));
    }

    /**
     * 社团查看匹配推荐
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:list')")
    @PostMapping("/viewClub/{matchingId}")
    public AjaxResult viewClubRecommendation(@PathVariable Long matchingId)
    {
        Long clubId = getUserId(); // 可根据实际情况调整获取方式
        return toAjax(crMatchingRecordService.viewClubRecommendation(matchingId, clubId));
    }

    /**
     * 获取推荐算法效果分析
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:list')")
    @GetMapping("/analysis")
    public AjaxResult getRecommendationAnalysis()
    {
        Map<String, Object> analysis = crMatchingRecordService.getRecommendationAnalysis();
        return success(analysis);
    }

    /**
     * 清理过期的匹配记录
     */
    @PreAuthorize("@ss.hasPermi('manage:matching:remove')")
    @Log(title = "清理过期匹配记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/cleanup")
    public AjaxResult cleanupExpiredMatchings(@RequestParam(defaultValue = "30") int days)
    {
        int cleanupCount = crMatchingRecordService.cleanupExpiredMatchings(days);
        return success("清理了 " + cleanupCount + " 条过期匹配记录");
    }
}